package com.itbaizhan.config;

/**
 * @author spf
 * @date 2024/2/13
 * @time 20:33
 */

import com.alibaba.fastjson.JSONObject;
import com.itbaizhan.result.Response;
import com.itbaizhan.utils.JWTUtils;
import io.netty.util.internal.StringUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 用户登录过滤器
 */
@Component
@ConfigurationProperties("org.my.jwt")
@Data
public class UserLoginGlobalFilter implements GlobalFilter, Ordered {

    // 跳过路由数组
    private String[] skipAuthUrls;

    /**
     * 过滤器逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 跳过路径
        String path = exchange.getRequest().getURI().getPath();
        if (skipAuthUrls != null){
            for (String skipAuthUrl : skipAuthUrls) {
                if (path.startsWith(skipAuthUrl)){
                    return chain.filter(exchange);
                }
            }
        }

        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtil.isNullOrEmpty(token)){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            Response res = new Response(500, "token参数缺失");
            byte[] responsebytes = JSONObject.toJSONString(res).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(responsebytes);
            return response.writeWith(Flux.just(buffer));
        }
        Boolean verify = JWTUtils.verify(token);
        if (!verify){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            Response res = new Response(500, "token参数无效");
            byte[] responsebytes = JSONObject.toJSONString(res).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(responsebytes);
            return response.writeWith(Flux.just(buffer));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
